<?php
load_plugin_textdomain('wp-surveys',$path='wp-content/plugins/wp-surveys');
include_once('includes/survey_meta.php');

function edit($survey_id) {
	global $wpdb, $blog_id, $current_user, $wp_surveys_tables;
	
	$survey_raw_data = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;",ARRAY_A);
	$survey = $survey_raw_data[0];

	$repost_value =  isset($_POST['repost']) && (ctype_digit(trim($_POST['repost']))) && (trim($_POST['repost'] != 0)) ? stripcslashes(trim($_POST['repost'])) : stripcslashes($survey['survey_repost']);

	$name_value = isset($_POST['name']) && (trim($_POST['name'] != '')) ? stripcslashes(trim($_POST['name'])) : stripcslashes($survey['survey_name']);

	$describe_value = isset($_POST['describe']) ? stripcslashes(trim($_POST['describe'])) : stripcslashes($survey['survey_describe']);
		
	$no_repost = isset($_POST['no_repost']) ? stripcslashes(trim($_POST['no_repost'])) : stripcslashes(get_survey_meta($survey['survey_id'], 'no_repost'));

	$user_report_type = isset($_POST['user_report_type']) ? stripcslashes(trim($_POST['user_report_type'])) : stripcslashes(get_survey_meta($survey['survey_id'], 'user_report_type'));

	$user_report = isset($_POST['user_report']) ? stripcslashes(trim($_POST['user_report'])) : stripcslashes(stripcslashes(get_survey_meta($survey['survey_id'], 'user_report')));
?>
	<div class="wrap">
		<h2><?php echo __('Edit Survey', 'wp-surveys');?></h2><br />
		<form action="" method="post" >
			<table class="widefat" id="the-list-x" width="100%" cellpadding="4" cellspacing="4">
				<tr valign="top">
					<td class="alternate" width="22%">
						<strong><?php echo __('Survey Title', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td class="alternate" width="78%">
						<textarea class="alternate-active" name="name" rows="1" cols="86"><?php echo $name_value;?></textarea>
						<br />
					</td>
				</tr>
				<tr valign="top">
					<td class="alternate" width="22%">
						<strong><?php echo __('Survey Description', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td class="alternate" width="78%">
						<textarea class="alternate-active" name="describe" rows="7" cols="86"><?php echo $describe_value;?></textarea>
						<br />
					</td>
				</tr>
				<tr valign="top">
					<td class="alternate" width="22%">
						&nbsp;
					</td>
					<td class="alternate" width="78%">
						<input class="alternate-active" onClick="if(this.checked){jQuery('#wp_surveys_repost').attr('disabled', 'disabled');}else{jQuery('#wp_surveys_repost').removeAttr('disabled');}" type="checkbox" name="no_repost" id="wp_surveys_no_repost" value="true"<?php echo $no_repost == 'true'?' checked="true"':'';?>/>
						<label for="wp_surveys_no_repost"><?php echo __('User may only complete this survey once.', 'wp-surveys');?></label>
						<br />
					</td>
				</tr>
				<tr valign="top" id="wp_surveys_repost_row">
					<td class="alternate" width="22%">
						<strong><?php echo __('Days until user can repost', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td class="alternate" width="78%">
						<input class="alternate-active" <?php echo $no_repost == 'true'?'disabled="disabled"':'';?> type="text" name="repost" id="wp_surveys_repost" value="<?php echo $repost_value;?>"/>
						<br />
					</td>
				</tr>
				<tr valign="top">
					<td class="alternate" width="22%">
						<strong><?php echo __('Survey User report', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td class="alternate" width="78%">
						<input class="alternate-active" onClick="if(this.checked){jQuery('#wp_surveys_report_template').attr('disabled', 'disabled');}" type="radio" name="user_report_type" id="wp_surveys_user_report_type_none" value="none"<?php echo $user_report_type =='none'?' checked="true"':'';?>/>
						<label for="wp_surveys_user_report_type_none"><?php echo __('No user report.', 'wp-surveys');?></label>
						<br />
						<input class="alternate-active" onClick="if(this.checked){jQuery('#wp_surveys_report_template').removeAttr('disabled');}" type="radio" name="user_report_type" id="wp_surveys_user_report_type_email" value="email"<?php echo $user_report_type =='email'?' checked="true"':'';?>/>
						<label for="wp_surveys_user_report_type_email"><?php echo __('Email report to user upon completion.', 'wp-surveys');?></label>
						<br />
						<input class="alternate-active" onClick="if(this.checked){jQuery('#wp_surveys_report_template').removeAttr('disabled');}" type="radio" name="user_report_type" id="wp_surveys_user_report_type_html" value="html"<?php echo $user_report_type =='html'?' checked="true"':'';?>/>
						<label for="wp_surveys_user_report_type_html"><?php echo __('Display report to user upon completion.', 'wp-surveys');?></label>
						<br />
						<input class="alternate-active" onClick="if(this.checked){jQuery('#wp_surveys_report_template').removeAttr('disabled');}" type="radio" name="user_report_type" id="wp_surveys_user_report_type_both" value="both"<?php echo $user_report_type =='both'?' checked="true"':'';?>/>
						<label for="wp_surveys_user_report_type_both"><?php echo __('Display and email generated user report to user upon completion..', 'wp-surveys');?></label>
						<br />
					</td>
				</tr>
				<style type="text/css">
					.wp_surveys_report_template_td li {
						list-style-type : disc;
						margin-left : 25px;
					}
				</style>
				<tr valign="top">
					<td class="alternate" width="22%">
						&nbsp;
					</td>
					<td class="alternate wp_surveys_report_template_td" width="78%">
						<a name="wp_survey_help" href="#wp_survey_help" onclick="jQuery('#wp_survey_help_div').css('display', jQuery('#wp_survey_help_div').css('display')=='none' ? 'block' : 'none');">Help</a><p/>
						<div id="wp_survey_help_div" class="widefat" style="display:none;padding:10px;">
							For examples of templating, go to <a href="http://www.smarty.net/">http://www.smarty.net/</a><p/>
							The following variables would be available for this report:
							<div style="padding-left : 25px;">
								<u>Lists</u><br/>
								<ul>
									<li>data - all result data</li>
									<li>usermeta - all user meta data</li>
									<li>groups</li>
								</ul><p/>
								<u>Group info</u><br/>
								<ul>
									<li>groups_SANITIZED_NAME_OF_GROUP_HERE_answer_weight</li>
									<li>groups_SANITIZED_NAME_OF_GROUP_HERE_answer_items (list of all responses that fall under this group)</li>
								</ul><p/>
								<i>Please note that SANITIZED_NAME_OF_GROUP_HERE will be replaced by the names of your groups in lower
								case with spaces replaced by underscores. <br/>
								Example: <b>My First Group</b> would become <b>my_first_group</b>, and the average answer weight
								would be accessable via the variable name <b>groups_my_first_group_answer_weight</b></i>.<p/>
								<u>List item fields:</u>
								<ul>
									<li>response_id</li>
									<li>user_id</li>
									<li>user_nicename</li>
									<li>user_email</li>
									<li>question_id</li> 
									<li>question_text</li>
									<li>question_group</li>
									<li>question_weight</li>
									<li>answer_id</li>
									<li>answer_text</li>
									<li>answer_weight_avg</li>
									<li>answer_weight_sum</li>
								</ul><p/>
								<u>Post content</u><br/>
								<p>
									Post content can be included by adding the following string:<br/>
									{post id="<b>ID</b>"}<br/>
									where <b>ID</b> is the ID value of the post which content you would like to include.
								</p>
								<p>
									Smarty template syntax may be used within posts, but posts cannot include other posts.
								</p>
								
								<u>Attaching files</u><br/>
								<p>
									Files can be attached (email only) in the following way:<br/>
									{attach file="<b>/absolute/path/on/server/to/file/to/attach</b>"}<br/>
								</p>
								
							</div>
						</div>
						<p/>
						<textarea <?php echo $user_report_type == 'none' ? 'disabled="disabled"' : '';?> class="alternate-active" name="user_report" id="wp_surveys_report_template" rows="10" cols="86"><?php echo $user_report;?></textarea>
						<br />
					</td>
				</tr>
<?php		
	/*echo '<tr valign="top"><td valign="top"><strong>'.__('Re-direct Link', 'wp-surveys').':&nbsp;<font color=red>'.__('Coming in V 8.0!', 'wp-surveys').'</font></strong><br/>'.__('Blank will display thank-you message', 'wp-surveys').'.<br/>[ '.__('NOTE: should start with http://', 'wp-surveys').' ] </td><td>';
	echo '<textarea class="alternate-active" name="go_url" rows="2" cols="42">'.stripcslashes($survey['survey_redirect_URL']).'</textarea><br /></td></tr>';
	echo '<tr valign="top"><td valign="top"><strong>'.__('Results are Public?', 'wp-surveys').' <font color=red>'.__('Coming in V 8.0!', 'wp-surveys').'</strong></font><br/>'.__('Yes, will display results page after completion', 'wp-surveys').'.<br/>'.__('Overrides redirect URL', 'wp-surveys').'.</td><td>';
	echo '<select name="public"><option value=0';
	if($survey['survey_share_results']=='0')
		echo ' selected="selected"';
	echo '>'.__('No', 'wp-surveys').'</option><option value=1';
	if($survey['survey_share_results']=='1')
		echo ' selected="selected"';
	echo '>'.__('Yes', 'wp-surveys').'</option></select></td></tr>';*/
	
	$questions = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['question']."` WHERE `survey_id`=".$survey_id.";",ARRAY_A);

	if($questions) {
		$open = $wpdb->get_var("SELECT `survey_open` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
?>		
				<tr>
					<td width="22%" align="center">
						<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
						<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
					</td>
					<td class="submit" width="78%"><input type="submit" name="wpsurv_submit" value="<?php echo __('Add More Questions', 'wp-surveys');?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Update', 'wp-surveys');?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __($open ? 'Retire' : 'Activate', 'wp-surveys')?>" />
					</td>
				</tr>
<?php 
		$i = 1;
		if (sizeof($questions)>0) foreach($questions as $question) {
?>
				<tr id="list-quest-<?php echo $i;?>" valign="top">
					<td class="alternate" align="right" width="22%">
						<strong><?php printf(__('Question %s:', 'wp-surveys'), $i);?></strong>
						<br />
<?php 
			if($question['question_type']=='one-vert')
				_e('Alignment Vertical', 'wp-surveys');
			elseif($question['question_type']=='one-hori')
				_e('Alignment Horizontal', 'wp-surveys');
			elseif($question['question_type']=='one-menu')
				_e('Alignment Menu', 'wp-surveys');
			/*elseif($question['question_type']=='mul-vert')
				_e('Choice - Multiple Answers (Vertical)', 'wp-surveys');
			elseif($question['question_type']=='mul-hori')
				_e('Choice - Multiple Answers (Horizontal)', 'wp-surveys');
			elseif($question['question_type']=='open-onep')
				_e('Open Ended - One Line w/Prompt', 'wp-surveys');
			elseif($question['question_type']=='open-more')
				_e('Open Ended - One or More Lines w/Prompt', 'wp-surveys');
			elseif($question['question_type']=='open-essa')
				_e('Open Ended - Essay', 'wp-surveys');
			elseif($question['question_type']=='open-date')
				_e('Open Ended - Date and/or Time', 'wp-surveys');
			else _e('Undefined type', 'wp-surveys');*/
?>
					</td>
					<td class="alternate" width="78%">
						<p>
<?php 
			$question_text = $question['question_text'];
			$question_text = stripcslashes(str_replace(array('\\"','\\'), array('"','')	, $question_text));
?>
							<textarea class="alternate-active" name="question_<?php echo $question['question_id'];?>_text" rows="7" cols="86"><?php echo $question_text;?></textarea>
						</p>
						<p>
							<table>
								<tr>
									<td class="alternate" align="left">
										<strong><?php echo __('Group (optional)', 'wp-surveys');?>:</strong>
										&nbsp;
									</td>
									<td>
										<input class="alternate-active" name="question_<?php echo $question['question_id'];?>_group" rows="2" cols="86" value="<?php echo stripcslashes($question['question_group']);?>"/>
									</td>
								</tr>
								<tr>
									<td class="alternate" align="left">
										<strong><?php echo __('Weight', 'wp-surveys');?>:</strong>
										&nbsp;
									</td>
									<td>
										<input class="alternate-active" name="question_<?php echo $question['question_id'];?>_weight" rows="2" cols="86" value="<?php echo stripcslashes($question['question_weight']);?>"/>
									</td>
								</tr>
							</table>				
						</p>
<?php 
			$i++;

			if(($question['question_type']=='one-vert') || ($question['question_type']=='one-hori') || ($question['question_type']=='one-menu') || ($question['question_type']=='mul-vert') || ($question['question_type']=='mul-hori')) {
				$empty_opts = $wpdb->get_var("SELECT count(answer_id) FROM `".$wp_surveys_tables['answer']."` WHERE `question_id`=".$question['question_id'].";");
?>
						<form action="" method="post">
							<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
							<input class="button" type="submit" name="wpsurv_submit" value="<?php echo _e($empty_opts == '0' ? 'Add Some Answers' : 'Edit or Add more Answers', 'wp-surveys');?>" />
							<input type="hidden" name="question_id" value="<?php echo $question['question_id'];?>" />
						</form>
<?php
			}
			//echo '<input type="submit" name="wpsurv_submit" value="'.__('Move Up', 'wp-surveys').'" />';
			//echo '<input type="submit" name="wpsurv_submit" value="'.__('Move Down', 'wp-surveys').'" />';
			//echo '<input type="submit" name="wpsurv_submit" value="'.__('Remove', 'wp-surveys').'" />';
?>
					</td>
				</tr>
<?php
		}
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') == false) {
			$open = $wpdb->get_var("SELECT `survey_open` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
?>
				<tr>
					<td width="22%" align="center">
						<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
						<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
					</td>
					<td class="submit">
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Add More Questions', 'wp-surveys');?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Update', 'wp-surveys');?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __($open ? 'Retire' : 'Activate', 'wp-surveys')?>" />
					</td>
				</tr>
<?php
		}
	} elseif(!$questions) {
		$open = $wpdb->get_var("SELECT `survey_open` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
?>
				<tr>
					<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
					<td width="22%" align="center">
						<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
					</td>
					<td class="submit">
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Add Some Questions', 'wp-surveys')?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Update', 'wp-surveys');?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __($open ? 'Retire' : 'Activate', 'wp-surveys')?>" />
					</td>
				</tr>
<?php
	}
?>
			</table>
		</form>
	</div>
<?php
}

function update($survey_id) {
	global $wpdb, $blog_id, $current_user, $wp_surveys_tables;
	
	$s_name = false; 
	$s_desc = false; 
	$s_repost = false; 
	$s_quest = false; 
	$fields = 0;
	
	$current_name = $wpdb->get_var("SELECT `survey_name` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
	
	if(trim($_POST['name']) == '') {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('ERROR!!', 'wp-surveys');?></strong></p>
		<p><strong><?php echo __('Question Title has been left empty!', 'wp-surveys');?></strong></p>
		<p><?php echo __('No changes has been made in the database', 'wp-surveys');?></p>
	</div>
<?php
		edit($_POST['survey_id']);
		return;
	} elseif($current_name != trim($_POST['name'])) {
		$s_name = true;
	} else {
		$fields++;
	}
	$current_describe = $wpdb->get_var("SELECT `survey_describe` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
	
	
	if($current_describe != trim($_POST['describe'])) {
		$s_desc = true;
	} else {
		$fields++;
	}
	
	//$current_url = $wpdb->get_var("SELECT `survey_redirect_URL` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
	//if($current_url != trim($_POST['go_url']))
	//$wpdb->query("UPDATE `".$wp_surveys_tables['survey']."` SET `survey_redirect_URL` = '".$wpdb->escape(trim($_POST['go_url']))."' WHERE `survey_id`=".$survey_id." LIMIT 1;");

/*
	$current_repost = $wpdb->get_var("SELECT `survey_repost` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
	
	if($current_repost != trim($_POST['repost'])) {
		if ((!ctype_digit(trim($_POST['repost']))) || (trim($_POST['repost']) == 0)) {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('ERROR!!', 'wp-surveys');?></strong></p>
		<p><strong><?php echo __('Days until user can repost must be a number bigger than zero!', 'wp-surveys');?></strong></p>
		<p><?php echo __('No changes has been made in the database', 'wp-surveys');?></p>
	</div>
<?php
			edit($_POST['survey_id']);
			return;
		} else { 
			$s_repost = true;
		}
	} else {
		$fields++;
	}
*/	
	$questions = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['question']."` WHERE `survey_id`=".$survey_id.";",ARRAY_A);
	
	if($questions) {
		$j = 1;
		if (sizeof($questions)>0) foreach($questions as $question) {
			$current_question_name = $question['text'];

			if(trim($_POST['question_'.$question['question_id'].'_text']) == '') {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('ERROR!!', 'wp-surveys');?></strong></p>
		<p><strong><?php printf(__('Question %s has been left empty!', 'wp-surveys'), $j);?></strong></p>
		<p><?php echo __('No changes has been made in the database', 'wp-surveys');?></p>
	</div>
<?php
				edit($_POST['survey_id']);
				return;
			} elseif(trim($_POST['question_'.$question['question_id'].'_text']) != $current_question_name) { 
				$s_quest = true;
			} else {
				$fields++;
			}
			$j++;
		}
	}
	
	$wpdb->query("UPDATE `".$wp_surveys_tables['survey']."` SET `survey_name` = '".$wpdb->escape(trim($_POST['name']))."', `survey_describe` = '".$wpdb->escape(trim($_POST['describe']))."', `survey_repost` = '".$wpdb->escape(trim($_POST['repost']))."' WHERE `survey_id`=".$survey_id." LIMIT 1;");

	set_survey_meta($survey_id, 'no_repost', isset($_POST['no_repost']) ? 'true' : 'false');
	set_survey_meta($survey_id, 'user_report_type', $wpdb->escape(trim($_POST['user_report_type'])));
	set_survey_meta($survey_id, 'user_report', $wpdb->escape(trim($_POST['user_report'])));

	$questions = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['question']."` WHERE `survey_id`=".$survey_id.";",ARRAY_A);

	if($questions) {
		if (sizeof($questions)>0) foreach ($questions as $question) {
			$wpdb->query("UPDATE `".$wp_surveys_tables['question']."` SET `question_text`='".$wpdb->escape(trim($_POST['question_'.$question['question_id'].'_text']))."', `question_group`='".$wpdb->escape(trim($_POST['question_'.$question['question_id'].'_group']))."', `question_weight`='".$wpdb->escape(trim($_POST['question_'.$question['question_id'].'_weight']))."' WHERE `question_id`=".$question['question_id']." LIMIT 1;");
		}
	}

?>
	<div id="message" class="updated fade">
		<h3><strong><?php echo __('Update Complete!', 'wp-surveys');?></strong></h3>
		<p><?php echo __('Changes have been applied', 'wp-surveys');?>.</p>
	</div>
<?php
	edit($_POST['survey_id']);
}
	
function update_answers($survey_id, $question_id) {
	global $wpdb, $blog_id, $current_user, $wp_surveys_tables;
	$fields = 0;

	$answer_identifiers = explode(',', $_POST['answer_identifiers']);
	$answer_ids = array();
	if (sizeof($answer_identifiers)>0) foreach($answer_identifiers as $identifier) {
		//echo $_POST['question_answer_id_'.$identifier].':';
		if ($_POST['question_answer_id_'.$identifier] == '') {
			$add_sql = "INSERT INTO `".$wp_surveys_tables['answer']."` (`answer_text`, `answer_weight`, `answer_css`, `question_id`, `survey_id`) VALUES ( '".$wpdb->escape(trim($_POST['question_answer_'.$identifier]))."', '".$wpdb->escape($_POST['question_answer_weight_'.$identifier])."', '".$wpdb->escape($_POST['question_answer_css_'.$identifier])."', '".$wpdb->escape($question_id)."', '".$wpdb->escape($survey_id)."');";
			$wpdb->query($add_sql);
			$answer_id = $wpdb->get_var('SELECT max(answer_id) from '.$wp_surveys_tables['answer']);
			array_push($answer_ids, $answer_id);
		} else {
			$add_sql = "UPDATE `".$wp_surveys_tables['answer']."` set `answer_text`='".$wpdb->escape(trim($_POST['question_answer_'.$identifier]))."', `answer_weight`='".$wpdb->escape(trim($_POST['question_answer_weight_'.$identifier]))."', `answer_css`='".$wpdb->escape(trim($_POST['question_answer_css_'.$identifier]))."' where answer_id=".$_POST['question_answer_id_'.$identifier].";";
			$wpdb->query($add_sql);
			array_push($answer_ids, $_POST['question_answer_id_'.$identifier]);
		}
	}
	if (sizeof($answer_ids)>0) {
		$sql = "DELETE FROM `".$wp_surveys_tables['answer']."` where question_id=".$question_id." and not answer_id in (".implode(',', $answer_ids).");";
		$wpdb->query($sql);
	}
	//$column = "question_forever";
	//$current_option = $wpdb->get_var("SELECT `".$column."` FROM `".$wp_surveys_tables['question']."` WHERE `question_id`=".$question_id." LIMIT 1;");
	//if($current_option != $_POST[$column])
		//$wpdb->query("UPDATE `".$wp_surveys_tables['question']."` SET `".$column."`='".$wpdb->escape($_POST[$column])."' WHERE `question_id`=".$question_id." LIMIT 1;");
?>
	<div id="message" class="updated fade">
		<h3><strong><?php echo __('Update Complete!', 'wp-surveys');?></strong></h3>
		<p class="submit"><?php echo __('Changes have been applied', 'wp-surveys');?></p>
		<form method="post" action="">
			<p class="submit">
				<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
				<input type="submit" name="wpsurv_submit" value="<?php echo __('Back to Edit Survey', 'wp-surveys');?>" />
			</p>
		</form>
		<p>
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Continue', 'wp-surveys');?>...</a>
		</p>
	</div>
<?php
}
	
function activate($survey_id) {
	global $wpdb, $wp_surveys_tables;

	$wpdb->query("UPDATE `".$wp_surveys_tables['survey']."` SET `survey_open`='1' WHERE `survey_id`= ".$survey_id." LIMIT 1;");
?>
	<div id="message" class="updated fade">
		<h3><strong><?php echo __('Activation Complete!', 'wp-surveys');?></strong></h3>
		<p><?php echo __('Changes have been applied', 'wp-surveys');?>.</p>
	</div>
<?php
	unset($_REQUEST["wpsurv_submit"]);
	manage_surveys();
}
		
function retire($survey_id) {
	global $wpdb, $wp_surveys_tables;

	$wpdb->query("UPDATE `".$wp_surveys_tables['survey']."` SET `survey_open`='0' WHERE `survey_id`= ".$survey_id." LIMIT 1;");
?>
	<div id="message" class="updated fade">
		<h3><strong><?php echo __('Retire Complete!', 'wp-surveys');?></strong></h3>
		<p><?php echo __('Changes have been applied', 'wp-surveys');?>.</p>
	</div>
<?php
	unset($_REQUEST["wpsurv_submit"]);
	manage_surveys();
}
	
function edit_answers($survey_id, $question_id) {
	global $wpdb, $wp_surveys_tables;

	$question_raw_data = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['question']."` WHERE `question_id`=".$question_id." LIMIT 1",ARRAY_A);
	$question = $question_raw_data[0];
	$empty_opts = 0;
	for($j = 0; $j < 10; $j++) {
		$opt = 'question_option_'.$j;
		if ($question[$opt] == '')
			$empty_opts++;
	}
	if($empty_opts != 10)
?>
	<div id="message" class="updated fade">
		<strong>CAUTION!</strong><br />	
		Removing answers on surveys that have already been in use will cause results to become invalid!<br /><br />
		<p><a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Back to manage surveys', 'wp-surveys');?>...</a></p>
	</div>
	<div class="wrap">
		<h2><?php echo __('Edit/Update Answers', 'wp-surveys');?></h2>
<?php
	
	$current_plugins = get_option('active_plugins');

	if((file_exists(ABSPATH . PLUGINDIR . '/polyglot.php')) && (in_array('polyglot.php', $current_plugins)))
		$polyglot = true;
	if($polyglot) {
?>
		<p>
			<strong><?php echo __('Question', 'wp-surveys');?>:</strong>
			&nbsp;&nbsp;
			<?php echo polyglot_filter(stripcslashes($question['question_text']));?>
		</p>
<?php
	} elseif(!$polyglot) {
?>
		<p>
			<strong><?php echo __('Question', 'wp-surveys');?>:</strong>
			&nbsp;&nbsp;
			<?php echo stripcslashes($question['question_text']);?>
		</p>
<?php
	}
?>
		<form action="" method="post">
			<input type="hidden" name="question_id" value="<?php echo $question_id;?>" />
			<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />

			<table id="the-list-x" width="100%" cellpadding="4" cellspacing="4">
				<tr valign="middle" id="question_answer_empty_row"></tr>
				<form method="post" action="">
					<tr>
						<td class="submit">
							<input type="button" onClick="add_survey_answer()" name="wpsurv_submit" value="<?php echo __('Add More Answers', 'wp-surveys');?>" />
						</td>
					</tr>
				</form>
<?php
	$current_question_answers = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['answer']."` WHERE `question_id`=".$question_id.";",ARRAY_A);
	$answer_output = '';
	if (sizeof($current_question_answers)>0) foreach ($current_question_answers as $answer){
		$answer_output .= '	add_survey_answer({answer_id:"'.$answer['answer_id'].'",answer_text:"'.$answer['answer_text'].'",answer_weight:"'.$answer['answer_weight'].'",answer_css:"'.$answer['answer_css'].'"});';
	}
?>
<script type="text/javascript">
jQuery(document).ready(function() {
<?php echo $answer_output;?>
});
<?php answer_item_template();?>
</script>
			</table>

			<input type="hidden" name="survey_id" value="<?php echo $survey_id;?> " />
			<input type="hidden" name="answer_identifiers" id="question_answer_identifiers" value="" />
			
			<table class="submit" width="100%" cellpadding="9" cellspacing="0">
				<tr>
					<td align="left">
						<input type="submit" onClick="submit_survey_answers()" name="wpsurv_submit" value="<?php echo __('Update Answers', 'wp-surveys');?>" />
					</td>
					<td align="right">
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Cancel', 'wp-surveys');?>" />
					</td>
					<td align="right">
						<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Back to manage surveys', 'wp-surveys');?>...</a>
					</td>
				</tr>
			</table>
		</form>
	</div>
<?php
}
	
function survey($survey_id, $name='', $desc='') {
?>
	<div class="wrap">
		<h2><?php echo __('Add a New Survey', 'wp-surveys');?></h2>
		<br />
		<form action="" method="post">
			<table width="100%" cellpadding="4" cellspacing="4">
				<tr valign="middle">
					<td class="alternate" align="center">
						<strong><?php echo __('Survey Title', 'wp-surveys');?>:</strong>
						&nbsp;&nbsp;
					</td>
					<td>
						<textarea class="alternate-active" name="name" rows="1" cols="86" ><?php echo stripcslashes($name);?></textarea>
					</td>
				</tr>
				<tr valign="middle">
					<td class="alternate" align="center">
						<strong><?php echo __('Description', 'wp-surveys');?>:</strong>
						&nbsp;&nbsp;
					</td>
					<td>
						<textarea class="alternate-active" name="describe" rows="3" cols="86" ><?php echo stripcslashes($desc);?></textarea>
					</td>
				</tr>
			</table>
			<p class="submit">
				<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
				<input type="submit" name="wpsurv_submit" value="<?php echo __('Add This Survey', 'wp-surveys');?>" />
			</p>
		</form>
		<br />
	</div>
<?php
}
	
function add_question($survey_id, $name='', $group='', $weight='', $type='0') {
?>
	<div class="wrap">
		<h2><?php echo __('Step 1: Define Question', 'wp-surveys');?>...</h2>
		
		<form action="" method="post"><br />
			<table class="widefat" width="100%" cellpadding="4" cellspacing="4">
				<tr valign="middle">
					<td class="alternate" align="center">
						<strong><?php echo __('Question', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td>
						<textarea class="alternate-active" name="name" rows="2" cols="86"><?php echo str_replace('\&quot;', '', stripcslashes($name));?></textarea>
					</td>
				</tr>
				<tr valign="middle">
					<td class="alternate" align="center">
						<strong><?php echo __('Group (optional)', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td>
						<input class="alternate-active" name="group" rows="2" cols="86" value="<?php echo stripcslashes($group);?>"/>
					</td>
				</tr>
				<tr valign="middle">
					<td class="alternate" align="center">
						<strong><?php echo __('Weight', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td>
						<input class="alternate-active" name="weight" rows="2" cols="86" value="<?php echo stripcslashes($weight);?>"/>
					</td>
				</tr>
				<tr valign="middle">
					<td class="alternate" align="center">
						<strong><?php echo __('Alignment', 'wp-surveys');?>:</strong>
						&nbsp;
					</td>
					<td>
						<select class="alternate" name="type">
<?php
	// THESE ARE THE questions that I hope to support in the ultimate version of the plugin.
	// The concepts are based off existing commercial survey software, but the functionality is 
	// duplicated with invented techniques. The commented Answers are only maintained for 
	// reference purposes. They are not functional in this version.
?>
							<option value="0" <?php if (($type == "0")) echo ' selected="selected"';?>>
								-- <?php echo __('Select answers alignment', 'wp-surveys');?> --
							</option>
							
							<option value="one-vert" <?php if (($type == "one-vert")) echo ' selected="selected"';?>>
								<?php echo __('Choice - Vertical', 'wp-surveys');?>
							</option>
							
							<option value="one-hori" <?php if (($type == "one-hori")) echo ' selected="selected"';?>>
								<?php echo __('Choice - Horizontal', 'wp-surveys');?>
							</option>
							
							<option value="one-menu" <?php if (($type == "one-menu")) echo ' selected="selected"';?>>
								<?php echo __('Choice - Menu', 'wp-surveys');?>
							</option>
							
<?php							
	//echo '<option value="mul-vert">'.__('Choice - Multiple Answers (Vertical)', 'wp-surveys').'</option>';
	//echo '<option value="mul-hori">'.__('Choice - Multiple Answers (Horizontal)', 'wp-surveys').'</option>';
	//<!--<option value="7">Matrix - One Answer per Row</option>-->
	//<!--<option value="20">Matrix - One Answer per Row (Rating Scale)</option>-->
	//<!--<option value="18">Matrix - Multiple Answers per Row</option>-->
	//<!--<option value="11">Matrix - Multiple Answers per Row (Menus)</option>-->
	//echo '<option value="open-onep">'.__('Open Ended - One Line w/Prompt', 'wp-surveys').'</option>';
	//echo '<option value="open-more">'.__('Open Ended - One or More Lines w/Prompt', 'wp-surveys').'</option>';
	//echo '<option value="open-essa">'.__('Open Ended - Essay', 'wp-surveys').'</option>';
	//<!--<option value="19">Open Ended - Constant Sum</option>-->
	//echo '<option value="open-date">'.__('Open Ended - Date and/or Time', 'wp-surveys').'</option>';
	//<!--<option value="1">Presentation - Descriptive Text</option>-->
	//<!--<option value="15">Presentation - Image</option>-->
	//<!--<option value="16">Presentation - Spacer</option>-->
?>
						</select>
					</td>
				</tr>
			</table>
			
			<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
			<p  class="submit">
				<input type="submit" name="wpsurv_submit" value="<?php echo __('Step 2', 'wp-surveys');?>" />
			</p>
		</form>
		<br />
	</div>
<?php

}
	
function step2($survey_id) {
	if((trim($_POST['name']) == '') && ($_POST['type'] == "0")) {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('Please, fill all fields!!', 'wp-surveys');?></strong></p>
	</div>
<?php
		add_question($survey_id, trim($_POST['name']), $_POST['type']);
	} elseif((trim($_POST['name'])) == '') {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('Please, fill Question field!!', 'wp-surveys');?></strong></p>
	</div>
<?php
		add_question($survey_id, trim($_POST['name']), $_POST['type']);
	} elseif(($_POST['type']) == "0") {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('Please, select answers Alignment!!', 'wp-surveys');?></strong></p>
	</div>
<?php 
		add_question($survey_id, trim($_POST['name']), $_POST['type']);
	} else {
?>
	<div class="wrap">
		<h2><?php echo __('Step 2: Create your question Answers', 'wp-surveys');?>...</h2>
		<br />
		
		<form action="" method="post">
			<?php echo __('Please list your Answers below.', 'wp-surveys');?>:
			<br />
			<br />

			<table id="the-list-x" width="100%" cellpadding="4" cellspacing="4">
				<tr valign="middle" id="question_answer_empty_row"></tr>
				<form method="post" action="">
					<tr>
						<td class="submit">
							<input type="button" onClick="add_survey_answer()" name="wpsurv_submit" value="<?php echo __('Add More Answers', 'wp-surveys');?>" />
						</td>
					</tr>
				</form>

<script type="text/javascript">
jQuery(document).ready(function() {
	add_survey_answer();
});
<?php answer_item_template();?>
</script>

<?php
		//if(($_POST['type']) == "open-date" || ($_POST['type']) == "open-essa" || ($_POST['type']) == "open-more" || ($_POST['type']) == "open-onep") {
			//_e('Your Answers are predefined for this type of question. Click submit to create question.', 'wp-surveys');
			//echo '<input type="hidden" name="rows" value="1" />';
			//for($i=0;$i<10;$i++)
				//echo '<input type="hidden" name="option'.$i.'" />';
			//}
?>
			</table>
			<input type="hidden" name="survey_id" value="<?php echo $survey_id?>" />
			<input type="hidden" name="answer_identifiers" id="question_answer_identifiers" value="" />
			<input type="hidden" name="type" value="<?php echo $_POST['type'];?>" />
			<input type="hidden" name="name" value="<?php echo trim($_POST['name']);?>" />
			<input type="hidden" name="group" value="<?php echo trim($_POST['group']);?>" />
			<input type="hidden" name="weight" value="<?php echo trim($_POST['weight']);?>" />
			<p class="submit">
				<input type="submit" onClick="submit_survey_answers()" name="wpsurv_submit" value="<?php echo __('Create Question', 'wp-surveys');?>" />
			</p>
		</form>
	</div>
<?php
	}
}
function answer_item_template() {
?>
var answerItemTemplate = new Array(
	'<tr valign="middle" id="question_answer_{answer_unique}">',
	'	<td>',
	'		<table class="widefat" id="the-list-x" width="100%" cellpadding="4" cellspacing="4">',
	'			<tr valign="middle" id="question_answer_answer_{answer_unique}">',
	'				<td class="alternate" align="center" width="22%">',
	'					<strong><?php printf(__("Answer", "wp-surveys"));?> <span id="question_answer_number_{answer_unique}">{answer_number}</span>:</strong>',
	'					&nbsp;',
	'				</td>',
	'				<td>',
	'					<textarea class="alternate-active" name="question_answer_{answer_unique}" rows="2" cols="86">{answer_text}</textarea>',
	'				</td>',
	'			</tr>',
	'			<tr valign="middle" id="question_answer_css_{answer_unique}">',
	'				<td class="alternate" align="center">',
	'					<strong><?php echo __("CSS Class (optional)", "wp-surveys");?>:</strong>',
	'					&nbsp;',
	'				</td>',
	'				<td>',
	'					<input class="alternate-active" name="question_answer_css_{answer_unique}" rows="2" cols="86" value="{answer_css}"/>',
	'				</td>',
	'			</tr>',
	'			<tr valign="middle" id="question_answer_weight_{answer_unique}">',
	'				<td class="alternate" align="center">',
	'					<strong><?php echo __("Weight (optional)", "wp-surveys");?>:</strong>',
	'					&nbsp;',
	'				</td>',
	'				<td>',
	'					<input class="alternate-active" name="question_answer_weight_{answer_unique}" rows="2" cols="86" value="{answer_weight}"/>',
	'					<input name="question_answer_id_{answer_unique}" type="hidden" value="{answer_id}"/>',
	'					<span class="submit"><input type="button" onClick="remove_survey_answer(\'{answer_unique}\'); return false;" name="wpsurv_submit" value="<?php echo __("Remove Answers", "wp-surveys");?>" /></span>',
	'				</td>',
	'			</tr>',
	'		</table>',
	'	</td>',
	'</tr>'
);
<?php	
}	
function create_question($survey_id) {
	global $wpdb, $wp_surveys_tables;

	$question_order = $wpdb->get_var('SELECT count(question_id) from '.$wp_surveys_tables['question'].' where survey_id='.$survey_id);
	$add_sql = "INSERT INTO `".$wp_surveys_tables['question']."` (`question_text`, `question_type`, `question_group`, `question_weight`, `question_order`, `survey_id`) VALUES ( '".$wpdb->escape(trim($_POST['name']))."', '".$wpdb->escape($_POST['type'])."', '".$wpdb->escape($_POST['group'])."', '".$wpdb->escape($_POST['weight'])."', '".$question_order."', '".$wpdb->escape($survey_id)."');";
	$wpdb->query($add_sql);

	$question_id = $wpdb->get_var('SELECT max(question_id) from '.$wp_surveys_tables['question']);

	$answer_identifiers = explode(',', $_POST['answer_identifiers']);
	if (sizeof($answer_identifiers)>0) foreach($answer_identifiers as $identifier) {
		$add_sql = "INSERT INTO `".$wp_surveys_tables['answer']."` (`answer_text`, `answer_weight`, `question_id`, `survey_id`) VALUES ( '".$wpdb->escape(trim($_POST['question_answer_'.$identifier]))."', '".$wpdb->escape($_POST['question_answer_weight_'.$identifier])."', '".$wpdb->escape($question_id)."', '".$wpdb->escape($survey_id)."');";
		$wpdb->query($add_sql);
	}
?>
	<div class="wrap">
		<h2><?php echo __('Step 3: Updating Database...', 'wp-surveys');?></h2>
	</div>
	<br />
	
	<div id="message" class="updated fade">
		<h3><strong><?php echo __('Complete!', 'wp-surveys');?></strong></h3>
		
		<form method="post" action="">
			<p class="submit">
				<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
				<input type="submit" name="wpsurv_submit" value="<?php echo __('Back to Edit Survey', 'wp-surveys');?>" />
			</p>
		</form>
		
		<p>
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Continue', 'wp-surveys');?>...</a>
		</p>
	</div>
<?php
}
	
function add_survey($survey_id) {
	global $current_user, $blog_id, $wp_surveys_tables;
	if(trim($_POST['name']) == '') {
?>
	<div id="message" class="updated fade">
		<p><strong><?php echo __('Please, fill Title field!!', 'wp-surveys');?> </strong></p>
	</div>
<?php
		survey($survey_id, trim($_POST['name']), trim($_POST['describe']));
	} else {
		global $wpdb;
//		if($wpdb->query("SELECT `survey_id` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_open` = '1';")) {
//			$wpdb->query("UPDATE `".$wp_surveys_tables['survey']."` SET `survey_open` = '0' WHERE `survey_open` = '1';");
//		}
		$this_sql = "INSERT INTO `".$wp_surveys_tables['survey']."` (`blog_id`, `user_id`, `survey_name`, `survey_describe`, `survey_open`) VALUES (".$blog_id.", ".$current_user->ID.", '".$wpdb->escape(trim($_POST['name']))."', '".$wpdb->escape(trim($_POST['describe']))."', 1);";
		if($wpdb->query($this_sql)) {
?>
	<div id="message" class="updated fade">
		<h3><strong><?php echo __('Survey succesfully created!', 'wp-surveys');?></strong></h3>
		<p><?php echo __('Thank You. A new survey has been added.', 'wp-surveys');?>.</p>
		<form method="post" action="">
			<p class="submit">
				<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
				<input type="submit" name="wpsurv_submit" value="<?php echo __('Add Some Questions', 'wp-surveys');?>" />
			</p>
		</form>
		<p>
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>"><?php echo __('Continue', 'wp-surveys');?>...</a>
		</p>
	</div>
<?php
		}
	}
}

function wp_survey_responses($survey_id) {
	global $wpdb, $wp_surveys_tables;
	
	$sql = "
		SELECT
			survey_name
		FROM
			".$wp_surveys_tables['survey']."
		WHERE
			survey_id = $survey_id
	";
	
	$survey_name = $wpdb->get_var($wpdb->prepare($sql));
	
	$sql = "
		SELECT
			r.response_id,
			u.user_login,
			r.response_datestamp
		FROM
			".$wp_surveys_tables['survey']." s
			INNER JOIN ".$wp_surveys_tables['response']." r ON r.survey_id = s.survey_id
			INNER JOIN ".$wp_surveys_tables['user']." u ON u.id = r.user_id
		WHERE
			s.survey_id = $survey_id
		ORDER BY
			r.response_datestamp desc 
	";

	$responses = $wpdb->get_results($wpdb->prepare($sql),ARRAY_A);
	if($responses) {
?>
	<div class="wrap">
		<h2><?php echo $survey_name.__(' Results', 'wp-surveys');?></h2>
		<p align="right">
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
		</p>
		
		<table class="widefat" id="the-list-x" width="100%" cellpadding="4" cellspacing="4">
			<tr>
				<th align="left"><?php echo __('User', 'wp-surveys');?></th>
				<th align="left"><?php echo __('Date', 'wp-surveys');?></th>
				<th></th>
			</tr>
<?php
			foreach($responses as $response) {
?>
			<tr class="alternate">
				<td>
					<?php echo $response['user_login'];?>
				</td>
				<td>
					<?php echo $response['response_datestamp'];?>
				</td>
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="previewPDF" value="1" />
						<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
						<input type="hidden" name="response_id" value="<?php echo $response['response_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('View Report', 'wp-surveys');?>" />
					</form>
			</tr>
<?php
			}			
?>

		</table>
		
		<p align="right">
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
		</p>
		
	</div>
<?php
	} else {
?>
		<p>
			There are no responses to this survey yet.
		</p>
		<p align="right">
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
		</p>
<?php
	}
}

function results($survey_id) {
	global $wpdb, $wp_surveys_tables;

	$questions = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['question']."` WHERE `survey_id`=".$survey_id.";",ARRAY_A);
	if($questions) {
?>
	<div class="wrap">
		<h2><?php echo __('Your Survey Results', 'wp-surveys');?></h2>
		<p align="right">
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
		</p>
		
		<table class="widefat" id="the-list-x" width="100%" cellpadding="4" cellspacing="4">
<?php			
		$current_plugins = get_option('active_plugins');

		if ((file_exists(ABSPATH . PLUGINDIR . '/polyglot.php')) && (in_array('polyglot.php', $current_plugins)))
			$polyglot = true;

		if (sizeof($questions)>0) foreach($questions as $question) {
			$answers = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['answer']."` WHERE `question_id`=".$question['question_id'].";",ARRAY_A);
			if(($question['question_type']=='one-vert' || $question['question_type']=='one-hori' || $question['question_type']=='one-menu' || $question['question_type']=='mul-vert' || $question['question_type']=='mul-hori')) {
/*				$all_responses = array("RESPONSESARRAY");
				$response_data = $wpdb->get_results("SELECT data_option FROM ".$data']." WHERE question_id = ".$question['question_id']." ORDER BY data_option", ARRAY_A);
				if($response_data) {
					if (sizeof($response_data)>0) foreach($response_data as $responses) {
						$mash_up=$responses['data_option'];    			       				   
						if($mash_up) {
							$these_responses = explode("|", $mash_up);
							if (sizeof($these_responses)>0) foreach($these_responses as $response)
								array_push($all_responses, trim($response));
						}
					}
				}
				$dropt = array_shift($all_responses);
				$first_answers = array("OPTIONARRAY");	
				$score_answers = array("0");
				$option_data = $wpdb->get_results("SELECT * FROM ".$wp_surveys_tables['question']." WHERE question_id = ".$question['question_id'], ARRAY_A);
				for($o=0;$o<10;$o++) {
					$option = "question_option_".$o;
					if($option_data[0][$option]) {
						$first_answers[] = $option_data[0][$option];
						array_push($score_answers, "0");
					}
				}
				//$forever = $option_data[0]['question_forever']; 
				//if($forever != '') {
					//$extra_answers = explode(",", $forever);  
					//foreach($extra_answers as $extra) {
						//array_push($first_answers, trim($extra));
						//array_push($score_answers, "0"); 
						//}
					//}
				array_push($first_answers, __('No response recorded', 'wp-surveys'));
				array_push($score_answers, "0");
					$all_answers = $first_answers;
				if (sizeof($all_responses)>0) foreach($all_responses as $count_response) {
					$key = array_search(trim($count_response), $all_answers);
					if($key)
						$score_answers[$key]++;
				}
				$running = 0;
				$totalscore = 0;
				if (sizeof($score_answers)>0) foreach($score_answers as $scores)       
					$totalscore = $totalscore + $scores;
*/

?>
			<tr>
				<td colspan="3">
					<u><?php echo __('Question', 'wp-surveys');?></u>:
					&nbsp;&nbsp;
					<strong><?php echo $polyglot?polyglot_filter($question['question_text']):$question['question_text'];?></strong>
				</td>
			</tr>
			<tr>
				<th style="width:100px;"><?php echo __('Responses', 'wp-surveys');?></th>
				<th><?php echo __('Answers', 'wp-surveys');?></th>
				<th style="width:100px;"><?php echo __('Weight', 'wp-surveys');?></th>
			</tr>
<?php

				if(sizeof($answers)) {
					foreach ($answers as $answer) {
						$responses = $wpdb->get_var("SELECT count(response_id) FROM `".$wp_surveys_tables['response_data']."` WHERE `answer_id`=".$answer['answer_id'].";");
					
?>
			<tr class="alternate">
				<td class="alternate">
					<?php echo $responses;?>
				</td>
				<td class="alternate">
					<?php echo $answer['answer_text'];?>
				</td>
				<td class="alternate">
					<?php echo $answer['answer_weight'];?>
				</td>
			</tr>
<?php
					}
				} else {
?>
			<form method="post" action="">
				<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />
				<input type="hidden" name="question_id" value="<?php echo $question['question_id'];?>" />

				<tr>
					<td class="submit" colspan="3">
						<strong><?php echo __('No answer(s) defined yet', 'wp-surveys');?>...</strong>
						&nbsp;&nbsp;
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Add Some Answers', 'wp-surveys');?>" />
					</td>
				</tr>
			</form>
<?php
				}
			}
			//if($question['question_type']=='open-more' || $question['question_type']=='open-onep' || $question['question_type']=='one-essa') {
				//echo '<tr><td><strong>'.$question['question_text'].'</strong></td><td></td></tr>';
				//if(!is_null($response_data)) {
					//foreach($response_data as $responses) {
						//if($score_answers[$running] != __('No Response Recorded', 'wp-surveys'))
							//echo '<tr><td>'.trim($responses['data_option']).'</td><td></td></tr>';
						//}
					//}
				//}
		}
?>
		</table>
		
		<p align="right">
			<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
		</p>
		
	</div>
<?php
	} elseif(!$questions) {
?>
	<form method="post" action="">
		<input type="hidden" name="survey_id" value="<?php echo $survey_id;?>" />

		<div id="message" class="updated fade">
			<h3><strong><?php echo __('There are no Question defined yet', 'wp-surveys');?></strong></h3>
			
			<p class="submit">
				<input type="submit" name="wpsurv_submit" value="<?php echo __('Add Some Questions', 'wp-surveys');?>" />
			</p>

			<p>
				<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];?>" ><?php echo __('Go back!', 'wp-surveys');?></a>
			</p>
		</div>
	</form>
<?php
		
	}
}

function results_CSV($survey_id) {
	global $wpdb, $wp_surveys_tables;
	
	header("Content-Type: text/plain");

	$sql = 	"SELECT distinct".
			"	rd.response_id, ".
			"	r.user_id, ".
			"	u.user_email, ".
			"	rd.question_id, ". 
			"	q.question_text, ".
			"	q.question_group, ".
			"	q.question_weight, ".
			"	rd.answer_id, ".
			"	a.answer_text, ".
			"	a.answer_weight ".
			
			"FROM ".
			"	".$wp_surveys_tables['response_data']." rd ".
			"	INNER JOIN ".$wp_surveys_tables['response']." r ON r.response_id=rd.response_id ".
			"	INNER JOIN ".$wp_surveys_tables['user']." u ON u.ID = r.user_id ".
			"	INNER JOIN ".$wp_surveys_tables['question']." q on q.question_id = rd.question_id ".
			"	INNER JOIN ".$wp_surveys_tables['answer']." a on a.answer_id = rd.answer_id ".

			"WHERE ".
			"	r.survey_id=".$survey_id." ".

			"ORDER BY ".
			"	r.user_id, r.response_id, q.question_id, a.answer_id";	
	$results = $wpdb->get_results($sql, ARRAY_A);
	$headings = false;

	if (sizeof($results) > 0) {
		foreach($results as $result) {
			$seperator = '';
			$row = '';
			if (!$headings) {
				foreach($result as $key => $field) {
					$row .= $seperator.'"'.$key.'"';
					$seperator=", ";
				}
				printf($row."\n");
				$seperator = '';
				$row = '';
				$headings = true;
			}
			foreach($result as $field) {
				$row .= $seperator.'"'.$field.'"';
				$seperator=", ";
			}
			printf($row."\n");
		}
	} else {
		echo 'No results available for this survey.';
	}
	exit;
}

function results_JSON($response_id) {
	global $wpdb, $wp_surveys_tables;

	$sql = 	"SELECT distinct".
			"	rd.response_id, ".
			"	r.user_id, ".
			"	u.user_email, ".
			"	rd.question_id, ". 
			"	q.question_text, ".
			"	q.question_group, ".
			"	q.question_weight, ".
			"	rd.answer_id, ".
			"	a.answer_text, ".
			"	a.answer_weight ".
			
			"FROM ".
			"	".$wp_surveys_tables['response_data']." rd ".
			"	INNER JOIN ".$wp_surveys_tables['response']." r ON r.response_id=rd.response_id ".
			"	INNER JOIN ".$wp_surveys_tables['user']." u ON u.ID = r.user_id ".
			"	INNER JOIN ".$wp_surveys_tables['question']." q on q.question_id = rd.question_id ".
			"	INNER JOIN ".$wp_surveys_tables['answer']." a on a.answer_id = rd.answer_id ".

			"WHERE ".
			"	r.response_id=".$response_id." ".

			"ORDER BY ".
			"	r.user_id, r.response_id, q.question_id, a.answer_id";	
	echo '/*'.$sql.'*/';
	$results = $wpdb->get_results($sql, ARRAY_A);

	$return_value = '';
	if (sizeof($results) > 0) {
		$item_seperator = '';
		$q = 1;
		foreach($results as $result) {
			$seperator = '';
			$item = '{';
			foreach($result as $key => $field) {
				$item .= $seperator.$key.':"'.$field.'"';
				$seperator=", ";
			}
			$item .= $seperator.'question_number:"'.$q.'"}';
			$return_value .= $item_seperator.$item;
			$item_seperator = ",\n";
			$q++;
		}
	}
	return '['.$return_value.']';
}

function wp_survey_assign_smarty_data($response_id, &$smarty, $survey_id = 0) {
	global $wpdb, $wp_surveys_tables;

	//expand as required.
	if ($response_id == '0') {
		$sql = "select max(response_id) from ".$wp_surveys_tables['response']." where survey_id=$survey_id";
		$response_id = $wpdb->get_var($sql);
	}
	
	$sql = 	"SELECT distinct".
			"	rd.response_id, ".
			"	r.user_id, ".
			" r.response_datestamp, ".
			"	u.user_nicename, ".
			"	u.user_email, ".
			"	rd.question_id, ". 
			"	q.question_text, ".
			"	q.question_group, ".
			"	q.question_weight, ".
			"	rd.answer_id, ".
			"	a.answer_text, ".
			"	a.answer_weight ".
			
			"FROM ".
			"	".$wp_surveys_tables['response_data']." rd ".
			"	INNER JOIN ".$wp_surveys_tables['response']." r ON r.response_id=rd.response_id ".
			"	INNER JOIN ".$wp_surveys_tables['user']." u ON u.ID = r.user_id ".
			"	INNER JOIN ".$wp_surveys_tables['question']." q on q.question_id = rd.question_id ".
			"	INNER JOIN ".$wp_surveys_tables['answer']." a on a.answer_id = rd.answer_id ".

			"WHERE ".
			"	r.response_id=".$response_id." ".

			"ORDER BY ".
			"	r.user_id, r.response_id, q.question_id, a.answer_id";	

	$results = $wpdb->get_results($sql, ARRAY_A);

	$group_sql = 
			"SELECT distinct".
			"	q.question_group, ".
			"	q.question_weight, ".
			"	avg(a.answer_weight) as answer_weight_avg, ".
			"	sum(a.answer_weight) as answer_weight_sum ".
			
			"FROM ".
			"	".$wp_surveys_tables['response_data']." rd ".
			"	INNER JOIN ".$wp_surveys_tables['question']." q on q.question_id = rd.question_id ".
			"	INNER JOIN ".$wp_surveys_tables['answer']." a on a.answer_id = rd.answer_id ".

			"WHERE ".
			"	rd.response_id=".$response_id." ".
			"GROUP BY ".
			"	q.question_group";
				
	$group_results = $wpdb->get_results($group_sql, ARRAY_A);
	//print_r($results);
//	echo sizeof($group_results);
//	echo $group_sql;

	$usermeta = array();
	if (count($results)) {
		$metas = $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = %d", $results[0]['user_id']) ,ARRAY_A);		
		foreach ($metas as $meta) {
			$usermeta[$meta['meta_key']] = $meta['meta_value']; 
		}
	}

	$smarty->assign('data', $results);
	$smarty->assign('usermeta', $usermeta);
	$smarty->assign('groups', $group_results);

	if (count($group_results)) {
		foreach ($group_results as $group_result) {
			$group_items = array();
	
			if (count($results)) {
				foreach ($results as $result) {
					if ($result['question_group'] == $group_result['question_group']) {
						array_push($group_items, $result);
					}
				}
			}
	
			$smarty->assign('group_'.sanitize_title($group_result['question_group']).'_answer_weight_avg', $group_result['answer_weight_avg']);
			$smarty->assign('group_'.sanitize_title($group_result['question_group']).'_answer_weight_sum', $group_result['answer_weight_sum']);
			$smarty->assign('group_'.sanitize_title($group_result['question_group']).'_items', $group_items);
		}
	}	
}
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
{
    if (!function_exists('xml_parser_create'))
    {
        return array ();
    }
    $parser = xml_parser_create('');

    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values)
        return; //Hmm...
    $xml_array = array ();
    $parents = array ();
    $opened_tags = array ();
    $arr = array ();
    $current = & $xml_array;
    $repeated_tag_index = array ();
    foreach ($xml_values as $data)
    {
        unset ($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value))
        {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value;
        }
        if (isset ($attributes) and $get_attributes)
        {
            foreach ($attributes as $attr => $val)
            {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }
        if ($type == "open")
        {
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
            {
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }
            else
            {
                if (isset ($current[$tag][0]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr']))
                    {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }
        elseif ($type == "complete")
        {
            if (!isset ($current[$tag]))
            {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else
            {
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes)
                    {
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        }
        elseif ($type == 'close')
        {
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}

function grab_tags($element_name, $xml, $content_only = true) {
    if ($xml == false) {
        return false;
    }
    $found = preg_match_all('#<'.$element_name.'(?:\s+[^>]+)?>(.*?)'.
            '</'.$element_name.'>#s', $xml, $matches);
    if ($found != false) {
        if ($content_only) {
            return $matches[1];  //ignore the enclosing tags
        } else {
            return $matches[0];  //return the full pattern match
        }
    }
    // No match found: return false.
    return false;
}

function grab_tag($element_name, $xml, $content_only = true, $index = 0) {
	$tags = grab_tags($element_name, $xml, $content_only);
	return $tags[$index];
}

?>